package org.zoomdev.zoom.dao.handler;

import org.zoomdev.zoom.dao.SqlConfig;
import org.zoomdev.zoom.dao.adapters.ResultSetMapping;
import org.zoomdev.zoom.dao.configs.Query;
import org.zoomdev.zoom.dao.entity.Entity;
import org.zoomdev.zoom.dao.entity.Field2ColumnMappingConfig;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public final class OneResultSetHandler implements ResultSetHandler {

    @SuppressWarnings("unchecked")
    @Override
    public Object fromResultSet(SqlConfig config, ResultSet rs) throws SQLException {
        if (rs.next()) {
            Entity<?> entity = config.getEntity();
            Query query = config.getQuery();
            List<Field2ColumnMappingConfig> list = query.getFields();
            ResultSetMapping<Object> mapping = query.getMapping();
            Object obj = BeanResultSetHandler.fromResultSet(config, entity, list, rs);
            if (mapping != null) {
                mapping.mapping(obj, rs);
            }
            return obj;
        }
        return null;
    }
}
